<template>
  <div class="g-input">
    <img v-if="leftIcon" class="g-input__left-icon" :src="leftIcon">
    <input
      :name="name"
      class="g-input__inner"
      :value="value"
      :maxlength="maxlength"
      :placeholder="placeholder"
      :placeholder-style="placeholderStyle"
      :disabled="disabled"
      :type="type"
      :auto-fill="autoFill"
      :cursor-spacing="cursorSpacing"
      :focus="focus"
      @input="onInput"
      @focus="onFocus"
      @blur="onBlur"
      @change="endComposing"
      @compositionstart="startComposing"
      @compositionend="endComposing"
    >
    <slot />
  </div>
</template>

<script lang="ts">
import Vue from 'vue'

export default Vue.extend({
  inheritAttrs: false,
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    placeholder: {
      type: String,
      default: '请输入'
    },
    placeholderStyle: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    leftIcon: {
      type: String,
      default: ''
    },
    maxlength: {
      type: Number,
      default: 100
    },
    type: {
      type: String,
      default: 'text'
    },
    autoFill: {
      type: String,
      default: ''
    },
    name: {
      type: String,
      default: ''
    },
    focus: {
      type: Boolean,
      default: false
    },
    cursorSpacing: {
      type: Number,
      default: 0
    }
  },
  methods: {
    onInput(event: Event) {
      // skip update value when composing
      if (!event.target!.composing) {
        this.updateValue((event.target as HTMLInputElement).value)
      }
    },
    onFocus() {
      this.$emit('focus')
    },
    onBlur(event: Event) {
      this.$emit('blur')
      this.endComposing(event)
    },
    updateValue(value: string) {
      this.$emit('input', value)
    },
    startComposing(event: Event) {
      event.target!.composing = true
    },
    endComposing(event: Event) {
      const { target } = event
      if (target!.composing) {
        target!.composing = false
      }
      this.onInput(event)
    }
  }
})
</script>

<style lang="less">
.g-input {
  display: flex;
  align-items: center;
  padding: 46px 0;
  box-shadow: inset 0px -1px 0px 0px #F5F5F5;
  box-sizing: border-box;
  &__left-icon {
    width: 46px;
    height: 46px;
    flex-shrink: 0;
    margin-right: 16px;
  }

  &__inner {
    flex: 1;
    width: 0;
    font-size: 32px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #222222;
    line-height: 46px;

    .input-placeholder {
      color: #CCCCCC;
      font-weight: 400;
      font-family: PingFangSC-Regular, PingFang SC;
    }
  }
}
</style>
